<template>
  <div>
    <Modal
      :title="isEdit?'编辑部门':'添加部门'"
      :value="value"
      @on-cancel="handleCancelClick"
      @on-ok="handleOkClick"
      @on-visible-change="handleVisibleChange"
      loading
    >
      <Form :label-width="60" :model="form" :rules="formRules" class="search-form" ref="form">
        <FormItem label="类型" prop="type">
          <RadioGroup v-model="form.type">
            <Radio :label="1">公司</Radio>
            <Radio :label="2">部门</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="名称" prop="name">
          <Input placeholder="请输入名称" v-model="form.name" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { departmentEdit, departmentSave } from '@/api/staff.js';
export default {
  model: {
    prop: 'value',
    event: 'on-visible-change'
  },
  props: {
    value: Boolean,
    isEdit: Boolean,
    oprNode: Object
  },
  data () {
    return {
      form: {
        type: '',
        name: ''
      },
      formRules: {
        type: [{ required: true, message: '请选择类型' }],
        name: [{ required: true, message: '请输入名称' }]
      }
    };
  },
  watch: {
    value: {
      handler: function (val) {
        if (val && this.isEdit) {
          this.form.type = this.oprNode.type;
          this.form.name = this.oprNode.nodeName;
        }
      },
      immediate: true
    }
  },
  methods: {
    handleVisibleChange (visible) {
      this.$emit('on-visible-change', visible);
    },
    async handleOkClick () {
      // this.$emit('on-visible-change', false);
      if (this.isEdit) {
        const data = {
          id: this.oprNode.nodeId,
          name: this.form.name,
          type: this.form.type
        };

        // console.log('编辑部门 data=>', data);
        await departmentEdit(data);
        this.$emit('on-save-success');
        this.$refs.form.resetFields();
      } else {
        const data = {
          parentid: this.oprNode.nodeId,
          name: this.form.name,
          type: this.form.type
        };

        // console.log('新增部门 data=>', data);
        await departmentSave(data);
        this.$emit('on-save-success');
        this.$refs.form.resetFields();
      }

      this.$emit('on-visible-change', false);
    },
    handleCancelClick () {
      this.$refs.form.resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .ivu-modal-body {
  padding: 30px 90px 20px 30px;
}
.page-wrapper {
  .ivu-page {
    float: right;
    margin: 10px 0;
  }
}
</style>
